import re
from datetime import datetime
from logger_config import get_logger

logger = get_logger(__name__)

def parse_agent_output(content):
    """解析代理输出中的标签，返回结构化的消息列表
    
    Args:
        content: 代理输出的原始内容
    
    Returns:
        解析后的消息列表，每个消息包含type和content字段
    """
    if not content or not isinstance(content, str):
        return [{'type': 'log', 'content': content}]
    
    parsed_items = []
    
    # 检查是否包含特定的标签模式
    patterns = {
        'thinking': r'<think>(.*?)</think>',
        'execution': r'<execute>(.*?)</execute>',
        'observation': r'<observation>(.*?)</observation>',
        'solution': r'<solution>(.*?)</solution>'
    }
    
    # 检查是否包含任何标签
    has_tags = any(re.search(pattern, content, re.DOTALL) for pattern in patterns.values())
    
    if not has_tags:
        # 如果没有标签，检查是否是特定的状态消息
        content_lower = content.lower().strip()
        
        # 检查是否是启动消息
        if any(keyword in content_lower for keyword in ['new task launched', '🚀 new task launched']):
            return [{'type': 'task_start', 'content': content}]
        
        # 检查是否是资源检索消息
        elif any(keyword in content_lower for keyword in ['retrieving resources', '🔍 retrieving resources']):
            return [{'type': 'resource_retrieval', 'content': content}]
        
        # 检查是否是代理启动消息
        elif any(keyword in content_lower for keyword in ['starting the agent', '⚙️ starting the agent']):
            return [{'type': 'agent_start', 'content': content}]
        
        # 检查是否是推理消息
        elif any(keyword in content_lower for keyword in ['reasoning', '🤔 reasoning']):
            return [{'type': 'reasoning', 'content': content}]
        
        # 检查是否是规划消息
        elif any(keyword in content_lower for keyword in ['planning', '⚙️ planning']):
            return [{'type': 'planning', 'content': content}]
        
        # 默认作为日志消息
        else:
            return [{'type': 'log', 'content': content}]
    
    # 解析包含标签的内容
    remaining_content = content
    
    # 按顺序查找和提取标签内容
    for tag_type, pattern in patterns.items():
        matches = re.finditer(pattern, remaining_content, re.DOTALL)
        for match in matches:
            tag_content = match.group(1).strip()
            if tag_content:
                if tag_type == 'thinking':
                    parsed_items.append({'type': 'reasoning', 'content': tag_content})
                elif tag_type == 'execution':
                    # 检查代码类型
                    code_type = 'python'  # 默认
                    if tag_content.strip().startswith('#!R'):
                        code_type = 'r'
                    elif tag_content.strip().startswith('#!BASH'):
                        code_type = 'bash'
                    
                    parsed_items.append({
                        'type': 'execution', 
                        'content': tag_content,
                        'code_type': code_type
                    })
                elif tag_type == 'observation':
                    parsed_items.append({'type': 'observation', 'content': tag_content})
                elif tag_type == 'solution':
                    parsed_items.append({'type': 'solution', 'content': tag_content})
            
            # 从剩余内容中移除已处理的标签
            remaining_content = remaining_content.replace(match.group(0), '', 1)
    
    # 处理剩余的非标签内容
    remaining_content = remaining_content.strip()
    if remaining_content:
        # 检查剩余内容是否包含特定的状态信息
        if 'Message' in remaining_content or 'Name:' in remaining_content:
            parsed_items.append({'type': 'log', 'content': remaining_content})
    
    # 如果没有解析到任何内容，返回原始内容
    if not parsed_items:
        parsed_items.append({'type': 'log', 'content': content})
    
    return parsed_items

def generate_execution_summary(log, result, query, execution_time, input_tokens=0, output_tokens=0):
    """生成执行过程的简洁总结
    
    Args:
        log: 执行日志列表
        result: 执行结果
        query: 用户查询
        execution_time: 执行时间（秒）
        input_tokens: 输入token数量
        output_tokens: 输出token数量
    
    Returns:
        执行总结字典
    """
    try:
        # 分析执行日志
        total_steps = len(log) if log else 0
        successful_steps = 0
        failed_steps = 0
        actions = []

        if log:
            for step in log:
                step_str = str(step)

                # 统计成功和失败步骤
                if 'error' in step_str.lower() or 'failed' in step_str.lower():
                    failed_steps += 1
                else:
                    successful_steps += 1

                # 提取工具调用
                if 'calling' in step_str.lower():
                    tool_match = re.search(r'calling\s+(\w+)', step_str, re.IGNORECASE)
                    if tool_match:
                        actions.append(f"调用工具: {tool_match.group(1)}")

                # 提取执行步骤
                if '<execute>' in step_str:
                    exec_content = re.search(r'<execute>(.*?)</execute>', step_str, re.DOTALL)
                    if exec_content:
                        exec_text = exec_content.group(1).strip()[:30]
                        actions.append(f"执行代码: {exec_text}...")

                # 提取思考过程
                if '<think>' in step_str:
                    think_content = re.search(r'<think>(.*?)</think>', step_str, re.DOTALL)
                    if think_content:
                        think_text = think_content.group(1).strip()[:30]
                        actions.append(f"分析思考: {think_text}...")

                # 提取观察结果
                if '<observation>' in step_str:
                    actions.append("获取执行结果")

        # 计算费用（简化计算，实际应该从数据库获取）
        total_tokens = input_tokens + output_tokens
        estimated_cost = total_tokens * 0.0001  # 简化的费用计算

        # 限制操作数量
        if len(actions) > 6:
            actions = actions[:6]
            actions.append(f"...还有{len(actions) - 6}个操作")

        summary = {
            'timestamp': datetime.now().isoformat(),
            'query': query[:80] + '...' if len(query) > 80 else query,
            'execution_time': f"{execution_time:.2f}",
            'total_steps': total_steps,
            'successful_steps': successful_steps,
            'failed_steps': failed_steps,
            'actions': actions,
            'total_tokens': total_tokens,
            'total_cost': f"{estimated_cost:.4f}",
            'status': 'completed' if failed_steps == 0 else 'partial_success'
        }

        return summary

    except Exception as e:
        logger.error(f"生成执行总结失败: {str(e)}")
        return {
            'timestamp': datetime.now().isoformat(),
            'query': query[:80] + '...' if len(query) > 80 else query,
            'execution_time': f"{execution_time:.2f}",
            'total_steps': 0,
            'successful_steps': 0,
            'failed_steps': 1,
            'actions': ['总结生成失败'],
            'total_tokens': 0,
            'total_cost': '0.0000',
            'status': 'summary_failed',
            'error': str(e)
        }

def create_api_response(data=None, success=True, message=None, error=None, status_code=200):
    """创建API响应
    
    Args:
        data: 响应数据
        success: 是否成功
        message: 响应消息
        error: 错误信息
        status_code: HTTP状态码
    
    Returns:
        格式化的响应字典和状态码
    """
    response = {
        'success': success,
        'timestamp': datetime.now().isoformat()
    }
    
    if message:
        response['message'] = message
    
    if data is not None:
        # 如果 data 是字典，将其内容合并到响应中
        if isinstance(data, dict):
            response.update(data)
        else:
            response['data'] = data
    
    if error:
        response['error'] = error
    
    return response, status_code

def format_api_response(data=None, success=True, message=None, error=None, status_code=200):
    """格式化API响应（向后兼容的别名）
    
    Args:
        data: 响应数据
        success: 是否成功
        message: 响应消息
        error: 错误信息
        status_code: HTTP状态码
    
    Returns:
        格式化的响应字典和状态码
    """
    return create_api_response(data, success, message, error, status_code)